package com.corpgovernment.organization.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.corpgovernment.api.applytrip.vo.AoApplyTripTempVo;
import com.corpgovernment.api.organization.dto.SwitchInfoDto;
import com.corpgovernment.api.organization.dto.SwitchValueDto;
import com.corpgovernment.api.organization.enums.SwitchEnum;
import com.corpgovernment.api.organization.model.org.response.GetOrgInfoResponseOld;
import com.corpgovernment.api.organization.model.switchinfo.*;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.common.enums.PayTypeEnum;
import com.corpgovernment.common.enums.TravelEnum;
import com.corpgovernment.common.operatelog.enums.PayConfigEnum;
import com.corpgovernment.common.operatelog.enums.SiteEnum;
import com.corpgovernment.organization.event.OrgInitEvent;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.corpgovernment.organization.dataloader.ApplyTripClientLoader;
import com.corpgovernment.organization.dataloader.db.MbOrgInfoLoader;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.CorpPayTypeEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.mapper.MbOrgTravelAttributeRelationMapper;
import com.corpgovernment.organization.model.SwitchConfigInfo;
import com.corpgovernment.organization.operatelog.service.enums.*;
import com.corpgovernment.organization.operatelog.service.pojo.PayConfigPojo;
import com.corpgovernment.organization.operatelog.service.pojo.PayPojo;
import com.corpgovernment.organization.operatelog.service.pojo.SwitchInfoPojo;
import com.corpgovernment.organization.service.*;
import com.ctrip.corp.obt.generic.event.core.EventCenter;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 开关相关
 *
 * @author qkdong
 */
@Service
@Slf4j
public class SwitchServiceImpl extends OrganizationBaseService implements ISwitchService {

    @Autowired
    private MbOrgTravelAttributeRelationMapper mbOrgTravelAttributeRelationMapper;
    @Autowired
    private ApplyTripClientLoader applyTripClientLoader;
    @Autowired
    private IOrgPayTypeService orgPayTypeService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private OrganizationApollo organizationApollo;
    @Autowired
    private MbOrgInfoLoader mbOrgInfoLoader;
    @Autowired
    private EventCenter eventCenter;
    @Autowired
    private GetAllSwitchService getAllSwitchService;

    private static List<String> payChannelList = CollUtil.newArrayList();

    static {

        payChannelList.add(PayTypeEnum.AliPay.getType());
        payChannelList.add(PayTypeEnum.WechatPay.getType());
        payChannelList.add(PayTypeEnum.UnionPay.getType());
        payChannelList.add(PayTypeEnum.TripAliPay.getType());
        payChannelList.add(PayTypeEnum.TripWechatPay.getType());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrgSwitch(SaveSwitchInfoRequest request) {
        if (request == null) {
            return;
        }
        GetSwitchListResponse getSwitchListResponse = new GetSwitchListResponse();
        getSwitchListResponse.setOrgId(request.getOrgId());
        //从apollo 获取开关信息
        List<SwitchInfoDto> defaultSwitchList = builderDefaultSwitchData(getSwitchListResponse);
        Map<String, String> kayMap = defaultSwitchList.stream().collect(Collectors.toMap(x -> x.getKey(), x -> x.getName(), (k1, k2) -> k1));
        MbOrgTravelAttributeRelation mbOrgTravelAttribute = null;
        List<MbOrgTravelAttributeRelation> addList = new ArrayList<>();
        List<MbOrgTravelAttributeRelation> updateList = new ArrayList<>();
        for (SwitchInfoVo switchInfoVo : request.getSwitchInfoList()) {
            mbOrgTravelAttribute = new MbOrgTravelAttributeRelation();
            mbOrgTravelAttribute.setIsDeleted(false);
            mbOrgTravelAttribute.setId(switchInfoVo.getId());
            mbOrgTravelAttribute.setOrgId(request.getOrgId());
            mbOrgTravelAttribute.setUid(request.getUId());
            mbOrgTravelAttribute.setSwitchKey(switchInfoVo.getKey());
            mbOrgTravelAttribute.setSwitchName(switchInfoVo.getName());
            mbOrgTravelAttribute.setExtendSwitch(JsonUtils.toJsonString(switchInfoVo.getExtendSwitch()));
            if (StringUtils.isBlank(switchInfoVo.getName())) {
                mbOrgTravelAttribute.setSwitchName(kayMap.get(switchInfoVo.getKey()));
            }
            mbOrgTravelAttribute.setValue(JsonUtils.toJsonString(switchInfoVo.getNowVal()));
            mbOrgTravelAttribute.setAllValues(JsonUtils.toJsonString(switchInfoVo.getAllValues()));
            if (mbOrgTravelAttribute.getId() == null) {  //新增
                mbOrgTravelAttribute.setDatachangeCreatetime(new Date());
                mbOrgTravelAttribute.setDatachangeLasttime(new Date());
                addList.add(mbOrgTravelAttribute);
            } else {
                updateList.add(mbOrgTravelAttribute); //更新
            }
        }
        if (CollectionUtils.isNotEmpty(addList)) {
            mbOrgTravelAttributeRelationMapper.insertList(addList);
        }
        if (CollectionUtils.isNotEmpty(updateList)) {
            mbOrgTravelAttributeRelationMapper.updateListSelective(updateList);
        }
    }

    @Override
    public GetSwitchListResponse getTravelAttributeSwitch(GetSwitchListRequest request) {
        GetSwitchListResponse response = new GetSwitchListResponse();
        response.setOrgId(request.getOrgId());
        response.setUId(request.getUId());
        List<SwitchInfoDto> defaultSwitchList = null;
        List<SwitchInfoVo> defaultTravelAttributeSwitchList = new ArrayList<>();
        //从apollo 查询开关默认值
        defaultSwitchList = builderDefaultSwitchData(response);
        log.info("查询默认的开关属性：{}", JsonUtils.toJsonString(defaultSwitchList));
        MbOrgSwitchRelation switchRelationParam = new MbOrgSwitchRelation();
        switchRelationParam.setOrgId(request.getOrgId());
        List<MbOrgTravelAttributeRelation> switchRelations = mbOrgTravelAttributeRelationMapper.getSwitchRelation(switchRelationParam.getOrgId(), switchRelationParam.getUId());
        // 传部门id如果查不到就用公司id
        if (CollectionUtils.isEmpty(switchRelations)){
            List<MbOrgInfo> mbOrgInfoList = mbOrgInfoLoader.selectByOrgIds(Collections.singletonList(switchRelationParam.getOrgId()));
            if (CollectionUtils.isNotEmpty(mbOrgInfoList) || StringUtils.isNotBlank(mbOrgInfoList.get(0).getParentId())){
                switchRelations = mbOrgTravelAttributeRelationMapper.getSwitchRelation(mbOrgInfoList.get(0).getParentId(), switchRelationParam.getUId());
            }
        }
        Map<String, SwitchInfoDto> defaultSwitchMap = defaultSwitchList.stream().filter(SwitchInfoDto::getShowFlag).collect(Collectors.toMap(SwitchInfoDto::getKey, x -> x, (k1, k2) -> k1));
        HashMap<String, SwitchInfoVo> switchKeyMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(switchRelations)) {
            //匹配开关和值,获得已保存的开关值
            SwitchInfoVo switchInfoVo = null;
            for (MbOrgTravelAttributeRelation orgSwitchRelation : switchRelations) {
                switchInfoVo = new SwitchInfoVo();
                switchInfoVo.setKey(orgSwitchRelation.getSwitchKey());
                switchInfoVo.setId(orgSwitchRelation.getId());
                switchInfoVo.setName(orgSwitchRelation.getSwitchName());
                SwitchInfoDto switchInfoDto = defaultSwitchMap.get(orgSwitchRelation.getSwitchKey());
                switchInfoVo.setExtendSwitch(convertorExtendSwitch(orgSwitchRelation.getExtendSwitch()));
                if (switchInfoDto != null) {
                    if (StringUtils.isBlank(orgSwitchRelation.getAllValues())) {
                        switchInfoVo.setAllValues(switchInfoDto.getAllValues());
                    } else {
                        switchInfoVo.setAllValues(JsonUtils.parse(orgSwitchRelation.getAllValues(), new TypeReference<LinkedHashMap<String, Object>>() {
                        }));
                    }
                    switchInfoVo.setNowVal(JsonUtils.parseArray(orgSwitchRelation.getValue(), Object.class));
                    switchKeyMap.put(switchInfoVo.getKey(), switchInfoVo);
                }
            }
        }
        log.info("查询到的数据:{} map:{}", JsonUtils.toJsonString(switchRelations), JsonUtils.toJsonString(switchKeyMap));
        //默认开关 获得未保存的默认开关值
        if (!CollectionUtils.isEmpty(defaultSwitchList)) {
            SwitchInfoVo data = null;
            SwitchInfoVo result = null;
            for (SwitchInfoDto switchInfoDto : defaultSwitchList) {
                if (!switchInfoDto.getShowFlag()) {
                    continue;
                }
                result = new SwitchInfoVo();
                data = switchKeyMap.get(switchInfoDto.getKey());
                if (data != null) {
                    result.setNowVal(data.getNowVal());
                    result.setId(data.getId());
                    result.setOrgId(data.getOrgId());
                    result.setName(data.getName());
                    result.setKey(data.getKey());
                    result.setExtendSwitch(data.getExtendSwitch());
                    //个别是不需要覆盖的，例如出差类型-》界面可以增删改查，这种就不覆盖
                    if (SwitchEnum.APPLICATION_TYPE_CONTROL.getKey().equals(data.getKey())
                            || SwitchEnum.APPLICATION_TEMPLATE.getKey().equals(data.getKey())) {
                        Map<String, Object> defaultAllValues = switchInfoDto.getAllValues();
                        Map<String, Object> baseAllValues = data.getAllValues();
                        Map<String, Object> newAllValues = new LinkedHashMap<>();
                        defaultAllValues.forEach((key, val) -> {
                            Object o = baseAllValues.get(key);
                            if (Objects.isNull(o)) {
                                newAllValues.put(key, val);
                            } else {
                                newAllValues.put(key, o);
                            }
                        });
                        result.setAllValues(newAllValues);
                    } else {
                        result.setAllValues(data.getAllValues());
                    }
                    result.setSort(switchInfoDto.getSort());
                } else {
                    result.setOrgId(switchInfoDto.getOrgId());
                    result.setNowVal((List<?>) switchInfoDto.getNowVal());
                    result.setKey(switchInfoDto.getKey());
                    result.setName(switchInfoDto.getName());
                    result.setAllValues(switchInfoDto.getAllValues());
                    result.setSort(switchInfoDto.getSort());
                }
                if(CollectionUtils.isEmpty(result.getExtendSwitch())){
                    result.setExtendSwitch(switchInfoDto.getExtendSwitch());
                }
                result.setShowFlag(true);
                result.setDefaultVal((List<?>) switchInfoDto.getNowVal());
                log.info("getTravelAttributeSwitch result:{}", JsonUtils.toJsonString(result));
                defaultTravelAttributeSwitchList.add(result);
            }
        }
        //根据apollo上面配置的sort进行排序，数据类型是double方便中途插入其他标签好排序。
        log.info("defaultTravelAttributeSwitchList排序前：{}", JsonUtils.toJsonString(defaultTravelAttributeSwitchList));
        defaultTravelAttributeSwitchList = defaultTravelAttributeSwitchList.stream().sorted(Comparator.comparing(SwitchInfoVo::getSort)).collect(Collectors.toList());
        log.info("defaultTravelAttributeSwitchList排序后：{}", JsonUtils.toJsonString(defaultTravelAttributeSwitchList));
        response.setSwitchInfoList(defaultTravelAttributeSwitchList);
        return response;
    }

    public SwitchInfoPojo convertPojo(SaveSwitchInfoRequest request) {
        GetSwitchListResponse response = new GetSwitchListResponse();
        response.setOrgId(request.getOrgId());
        List<SwitchInfoDto> defaultSwitchList = builderDefaultSwitchData(response);
        SwitchInfoPojo switchInfoPojo = new SwitchInfoPojo();
        if (CollectionUtils.isNotEmpty(defaultSwitchList)) {
            StringBuilder stringBuilder = null;
            for (SwitchInfoDto switchInfoDto : defaultSwitchList) {
                if (!switchInfoDto.getShowFlag()) {
                    continue;
                }
                List<?> nowVal = (List<?>) switchInfoDto.getNowVal();
                Object o = nowVal.get(0);
                if (SwitchEnum.APPLICATIONCONTROL.getKey().equals(switchInfoDto.getKey())) {//出差申请管控方式
                    switchInfoPojo.setApplyTrip(ManagementControlEnum.get(o.toString()).getDesc());
                } else if (SwitchEnum.APPLICATION_TIME_CONTROL.getKey().equals(switchInfoDto.getKey())) {//预订时间管控
                    String msg = "出差申请单时间有效期内前后{0}天可进行相关行程预订";
                    switchInfoPojo.setTimeControl(msg.replace("{0}", o.toString()));
                } else if (SwitchEnum.APPLICATION_TEMPLATE.getKey().equals(switchInfoDto.getKey())) { //申请单模板类型
                    switchInfoPojo.setTemplate(TemplateEnum.get(o.toString()).getDesc());
                } else if (SwitchEnum.APPLICATION_TYPE.getKey().equals(switchInfoDto.getKey())) {//出差类型
                    Map<String, Object> allValues = defaultSwitchList.get(4).getAllValues();
                    stringBuilder = new StringBuilder();
                    for (Object obj : nowVal) {
                        stringBuilder.append(allValues.get(obj)).append(",");
                    }
                    stringBuilder = stringBuilder.indexOf(",") != -1 ? stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(",")) : stringBuilder;
                    switchInfoPojo.setTravelType(String.valueOf(stringBuilder));
                } else if (SwitchEnum.TRAFFICCONTROL.getKey().equals(switchInfoDto.getKey())) {//交通工具递次控制
                    switchInfoPojo.setTrafficControl(TrafficControlEnum.get(o.toString()).getDesc());
                } else if (SwitchEnum.TRAFFICMANAGE.getKey().equals(switchInfoDto.getKey())) {
                    stringBuilder = new StringBuilder();
                    for (Object os : nowVal) {
                        stringBuilder.append(TrafficManageEnum.get(os.toString()).getDesc()).append(">");
                    }
                    stringBuilder = stringBuilder.indexOf(">") != -1 ? stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(">")) : stringBuilder;
                    switchInfoPojo.setTrafficManage(stringBuilder.toString());
                } else if (SwitchEnum.ATTR_HIGHEST_STARND_MANAGE.getKey().equals(switchInfoDto.getKey())) {//是否按同行最高标准控制
                    switchInfoPojo.setHighestStrandManage(HighestStrandManageEnum.get(o.toString()).getDesc());
                } else if (SwitchEnum.ATTR_REIMBURSEMENT_CONTROL.getKey().equals(switchInfoDto.getKey())) {//报账模式
                    switchInfoPojo.setReimbursementControl(LeaveControlEnum.get(o.toString()).getDesc());
                } else if (SwitchEnum.ATTR_FLIGHT_CLASS_CONTROL.getKey().equals(switchInfoDto.getKey())) {//国内机票多服务商聚合方式
                    switchInfoPojo.setFlightClassControl(FlightClassControlEnum.get(o.toString()).getDesc());
                }
            }
        }
        return switchInfoPojo;
    }

    @Override
    public SwitchInfoSoa getSwitchInfo(GetSwitchListRequest request) {
        //根据key 查询开关id
        List<MbOrgTravelAttributeRelation> orgSwitchRelations = mbOrgTravelAttributeRelationMapper.getSwitchRelationByOrgIds(Arrays.asList(request.getOrgId()), request.getSwitchKey());
        GetSwitchListResponse response = new GetSwitchListResponse();
        response.setOrgId(request.getOrgId());
        response.setUId(request.getUId());
        List<SwitchInfoDto> defaultSwitchList = builderDefaultSwitchData(response);

        SwitchInfoDto defaultSwitchInfoVo = defaultSwitchList.stream().filter(x -> request.getSwitchKey().equals(x.getKey())).findFirst().orElse(null);
        MbOrgTravelAttributeRelation orgSwitchRelation = null;
        Map<String, Object> map = null;
        if (defaultSwitchInfoVo != null) {
            map = defaultSwitchInfoVo.getAllValues();
        }
        if (defaultSwitchInfoVo == null && CollectionUtils.isEmpty(orgSwitchRelations)) {
            return null;
        }
        SwitchValueDto valueDto = null;
        SwitchInfoSoa switchInfoSoa = null;
        if (!CollectionUtils.isEmpty(orgSwitchRelations)) {
            orgSwitchRelation = orgSwitchRelations.get(0);
            switchInfoSoa = new SwitchInfoSoa();
            BeanUtils.copyProperties(orgSwitchRelation, switchInfoSoa);
            return switchInfoSoa;
        } else if (defaultSwitchInfoVo != null) {
            switchInfoSoa = new SwitchInfoSoa();
            switchInfoSoa.setValue(JsonUtils.toJsonString(defaultSwitchInfoVo.getNowVal()));
            switchInfoSoa.setAllValues(defaultSwitchInfoVo.getAllValues());
            switchInfoSoa.setSwitchKey(defaultSwitchInfoVo.getKey());
            switchInfoSoa.setSwitchName(defaultSwitchInfoVo.getName());
            switchInfoSoa.setUid(defaultSwitchInfoVo.getUId());
            switchInfoSoa.setOrgId(request.getOrgId());
        } else {
            return null;
        }

        return switchInfoSoa;
    }

    @Override
    public GetAllSwitchResponse allSwitch(GetSwitchListRequest request) {
     return getAllSwitchService.allSwitch(request.getOrgId(), request.getUId());
    }

    @Override
    public void saveOrgSwitchSoa(SwitchInfoSoa request) {
        if (request == null) {
            return;
        }
        MbOrgTravelAttributeRelation mbOrgTravelAttributeRelation = new MbOrgTravelAttributeRelation();
        BeanUtils.copyProperties(request, mbOrgTravelAttributeRelation, "allValues");
        mbOrgTravelAttributeRelation.setId(request.getSwitchId());
        mbOrgTravelAttributeRelation.setAllValues(JsonUtils.toJsonString(request.getAllValues()));
        if (mbOrgTravelAttributeRelation.getId() == null) {
            mbOrgTravelAttributeRelationMapper.insertSelective(mbOrgTravelAttributeRelation);
        } else {
            mbOrgTravelAttributeRelationMapper.updateByPrimaryKeySelective(mbOrgTravelAttributeRelation);
        }
    }

    @Override
    public void savePayConfigInfo(PayConfigRequest request) {
        String orgId = request.getOrgId();
        List<GetOrgInfoResponseOld.OrgPayType> list = request.getList();
        String requestType = request.getType();
        for (GetOrgInfoResponseOld.OrgPayType orgPayType : list) {
            if (orgPayType != null && CorpPayTypeEnum.PUB.toString().equalsIgnoreCase(orgPayType.getCorpPayType())) {
                if (OrgTypeEnum.C.getCode().equalsIgnoreCase(requestType)) {
                    List<String> paytype = orgPayType.getPaytype();
                    if (CollectionUtils.isEmpty(paytype)) {
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.PAY_TYPE_IS_NULL);
                    }
                }
            }
        }
        List<String> orgIds = Lists.newArrayList();
        orgIds.add(orgId);
        //先删除，在保存
        orgPayTypeService.delete(orgIds, null, null, null, true);
        String corpPayType;
        List<String> payTypeList;
        String site;
        List<MbOrgPayType> mbOrgPayTypeList = Lists.newArrayList();
        MbOrgPayType mbOrgPayType;
        for (GetOrgInfoResponseOld.OrgPayType payType : list) {
            corpPayType = payType.getCorpPayType();
            payTypeList = payType.getPaytype();
            site = payType.getSite();
            if (CollectionUtils.isNotEmpty(payTypeList)) {
                for (String type : payTypeList) {
                    mbOrgPayType = new MbOrgPayType(orgId, corpPayType, type, site);
                    mbOrgPayTypeList.add(mbOrgPayType);
                }
            } else {
                mbOrgPayType = new MbOrgPayType(orgId, corpPayType, null, site);
                mbOrgPayTypeList.add(mbOrgPayType);
            }
        }
        orgPayTypeService.batchSavePayType(mbOrgPayTypeList);
    }

    @Override
    public List<GetOrgInfoResponseOld.OrgPayType> getPayConfigInfo(GetPayConfigRequest request) {
        String orgId = request.getOrgId();
        List<MbOrgPayType> payList = orgPayTypeService.findOrgPayTypeByOrgId(orgId);
        log.info("******payList:{}",payList);
        List<GetOrgInfoResponseOld.OrgPayType> payTypeList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(payList)) {
            //是否增补
            boolean result = commonService.supplementSite(request, payList);
            log.info("是否增补：{}",request);
            //重新查询增补数据
            if (result) {
                payList = orgPayTypeService.findOrgPayTypeByOrgId(orgId);
            }
            log.info("重新查询增补数据：{}",payList);
            return commonService.returnData(payList, payTypeList, orgId);
        }
        String type = request.getType();
        List<String> typeList = Lists.newArrayList(OrgTypeEnum.C.getCode(), OrgTypeEnum.D.getCode());
        if (typeList.contains(type)) {
            //初始化组织设置
            OrgInitEvent orgInitEvent = new OrgInitEvent();
            OrgInitEvent.InitOrgPayType initOrgPayType = new OrgInitEvent.InitOrgPayType();
            initOrgPayType.setOrgId(orgId);
            initOrgPayType.setOrgType(type);
            orgInitEvent.setInitOrgPayType(initOrgPayType);
            eventCenter.post(orgInitEvent);
        } else {
            log.error("组织类型错误:{}", type);
            return payTypeList;
        }
        payList = orgPayTypeService.findOrgPayTypeByOrgId(orgId);
        return commonService.returnData(payList, payTypeList, orgId);
    }


    public PayPojo convertPayConfig(GetPayConfigRequest getPayConfigRequest) {
        List<GetOrgInfoResponseOld.OrgPayType> configInfo = getPayConfigInfo(getPayConfigRequest);
        if (CollectionUtils.isNotEmpty(configInfo)) {
            List<PayConfigPojo> payConfigPojoList = Lists.newArrayList();
            PayConfigPojo payConfigPojo;
//            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer s;
            for (GetOrgInfoResponseOld.OrgPayType payType : configInfo) {
                payConfigPojo = new PayConfigPojo();
                s = new StringBuffer();
                s.append(SiteEnum.get(payType.getSite()).getDesc()).append("-").append(TravelEnum.getByType(payType.getCorpPayType()).getDesc());
                payConfigPojo.setSite(s.toString());
                if (CollectionUtils.isNotEmpty(payType.getPaytype())) {
                    StringBuffer sb = new StringBuffer();
                    for (String type : payType.getPaytype()) {
                        sb.append(PayConfigEnum.get(type).getDesc());
                        sb.append(",");
                    }
                    if (sb != null) {
                        sb = sb.deleteCharAt(sb.lastIndexOf(","));
                        payConfigPojo.setPaytype(sb.toString());
                    }
                }
                payConfigPojoList.add(payConfigPojo);
//                stringBuffer.append(payConfigPojo.getSite()).append("、").append(payConfigPojo.getCorpPayType()).append("、").append(payConfigPojo.getPaytype()).append("、");
            }
//            stringBuffer = stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("、"));
            PayPojo payPojo = new PayPojo();
            payPojo.setList(payConfigPojoList);
            return payPojo;
        }
        return null;
    }


    @Override
    public List<PayInfoResponse> getUserPayInfo(PayInfoRequest request) {
        // 查询支付方式
        String orgId = request.getOrgId();
        List<PayInfoResponse> payInfoList = Lists.newArrayList();
        String transport = request.getTransport();
        String name = request.getName();
        List<MbOrgPayType> mbOrgPayTypeList = orgPayTypeService.findPayTypeList(orgId, transport, name);
        if (CollectionUtils.isNotEmpty(mbOrgPayTypeList)) {
            MbOrgInfo orgInfo = organizationInfoService.findByOrgId(orgId);
            if (orgInfo != null
                    && OrgTypeEnum.D.getCode().equalsIgnoreCase(orgInfo.getOrgType())
                    && CorpPayTypeEnum.PUB.toString().equalsIgnoreCase(name)) {
                MbOrgPayType mbOrgPayType = mbOrgPayTypeList.get(0);
                if (mbOrgPayType != null && StringUtils.isBlank(mbOrgPayType.getPaytype())) {
                    MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
                    if (mbOrgInfo == null) {
                        log.error("直属公司查询为空");
                        return payInfoList;
                    }
                    orgId = mbOrgInfo.getOrgId();
                    mbOrgPayTypeList = orgPayTypeService.findPayTypeList(orgId, transport, name);
                    if (CollectionUtils.isEmpty(mbOrgPayTypeList)) {
                        log.error("直属公司支付方式为空");
                        return payInfoList;
                    }
                }
            }
        } else {
            log.error("获取支付方式失败,orgId={},transport={},name={}",orgId, transport, name);
            return payInfoList;
        }

        PayInfoResponse payInfoResponse;
        String payType;
        if (CollectionUtils.isNotEmpty(mbOrgPayTypeList)) {
            for (MbOrgPayType mbOrgPayType : mbOrgPayTypeList) {
                payType = mbOrgPayType.getPaytype();
                payInfoResponse = new PayInfoResponse(mbOrgPayType.getCorpPayType(), payType);
                if (PayTypeEnum.PPAY.getType().equalsIgnoreCase(payType)) {
                    payInfoResponse.setType(payChannelList);
                } else {
                    payInfoResponse.setType(Lists.newArrayList());
                }
                payInfoList.add(payInfoResponse);
            }
        } else {
            log.info("获取因公因私类型失败");
            return payInfoList;
        }
        return payInfoList;
    }


    /**
     * 获取配置key的list
     *
     * @return
     */
    private List<SwitchInfoDto> builderDefaultSwitchData(GetSwitchListResponse response) {
        List<SwitchConfigInfo> switchConfigInfos = JsonUtils.parseArray(organizationApollo.getConfigSwitchinfoList(), SwitchConfigInfo.class);
        List<SwitchInfoDto> switchInfoList = new ArrayList<>();
        if (switchConfigInfos == null) {
            return switchInfoList;
        }
        for (SwitchConfigInfo switchConfigInfo : switchConfigInfos) {
            SwitchInfoDto switchInfoDto = new SwitchInfoDto();
            switchInfoDto.setNowVal(switchConfigInfo.getDefaultVal());
            switchInfoDto.setName(switchConfigInfo.getName());
            switchInfoDto.setAllValues(switchConfigInfo.getAllValues());
            switchInfoDto.setKey(switchConfigInfo.getKey());
            switchInfoDto.setShowFlag(switchConfigInfo.getShowFlag());
            switchInfoDto.setSort(switchConfigInfo.getSort());
            switchInfoDto.setExtendSwitch(switchConfigInfo.getExtendSwitch());
            //获取出差申请模版列表
            if (SwitchEnum.APPLICATION_TEMPLATE.getKey().equals(switchConfigInfo.getKey())) {
                //switchInfoDto.setAllValues(getApplyTripTemplateList(response.getOrgId()));
            }

            switchInfoList.add(switchInfoDto);
        }
        return switchInfoList;
    }

    /**
     * 获取出差申请模版列表
     *
     * @return
     */
    private Map<String, Object> getApplyTripTemplateList(String orgId) {
        List<AoApplyTripTempVo> aoApplyTripTempList = applyTripClientLoader.listApplyTripTempList(orgId);
        if (CollectionUtils.isEmpty(aoApplyTripTempList)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();
        for (AoApplyTripTempVo item : aoApplyTripTempList) {
            map.put(item.getId().toString(), item.getTempName());
        }
        return map;
    }

    /**
     * extend_switch json转换成对象
     * @param extendSwitchJson
     * @return
     */
    public List<Object> convertorExtendSwitch(String extendSwitchJson){
        if(StringUtils.isBlank(extendSwitchJson)){
            return null;
        }
        return JsonUtils.parseArray(extendSwitchJson, Object.class);
    }

}
